<?php
/**
 * Created by IntelliJ IDEA.
 * User: ty42
 * Date: 6/12/16
 * Time: 3:15 PM
 */


class Posttitlem extends CI_Model
{
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 根据职称ID获取职称名字
     * @param $posttitle_id
     * @param bool $is_critical
     * @return string
     */
    public function getPosttitleName($posttitle_id, $is_critical = false)
    {

        $key = 'redis_post_name_list_getPosttitleName' . $posttitle_id;
        $res = $this->redis->get($key);
        if ($res) $posttitle_list = unserialize($res);
        if (empty($posttitle_list)) {
            $posttitle_list = $this->getPosttitleList();
            $result_ = serialize($posttitle_list);
            $this->redis->save($key, $result_, 200);
        }

        $posttitle_name = '其它';
        if (isset($posttitle_list[$posttitle_id])) {
            $posttitle_name = $posttitle_list[$posttitle_id];
        }
        elseif (in_array($posttitle_id, $posttitle_list)) {
            $posttitle_name = $posttitle_id;
        }
        elseif (! is_numeric($posttitle_id) && ! $is_critical) {
            $posttitle_name = $posttitle_id;
        }

        return $posttitle_name;
    }


    /**
     * 根据职称名字获取职称ID
     * @param $posttitle_name
     * @return int|''
     */
    public function getPosttitleID($posttitle_name)
    {
        $posttitle_list = $this->getPosttitleList();

        if (isset($posttitle_list[$posttitle_name])) {
            $posttitle_id = $posttitle_name;
        }
        else {
            $posttitle_id = array_search($posttitle_name, $posttitle_list);
            $posttitle_id = $posttitle_id ? $posttitle_id : 0;
        }

        return $posttitle_id;
    }


    /**
     * 获取职称列表
     */
    public function getPosttitleList()
    {
        $key = POSTTITLE_LIST_PREFIX;
        $list = unserialize($this->redis->get($key));
        if (!$list) {
            $result = $this->db->select('ptid, ptname')
                ->from('ml_posttitle')
                ->where(array('is_show' => 1))
                ->get()
                ->result_array();
            $list = array_column($result, 'ptname', 'ptid');

            $this->redis->save($key, serialize($list), POSTTITLE_LIST_KEY_EXPIRE_TIME);
        }

        return $list;
    }
}